package com.ag.admin.dao;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.ag.bean.TbUser;
import com.ag.common.IDUtil;
import com.ag.dao.TbUserDAO;

@Repository("adminTbUserDAO")
public class AdminTbUserDAO extends TbUserDAO {
	private static final Logger logger = Logger.getLogger(AdminTbUserDAO.class);

	private SessionFactory sessionFacotry;

	@Resource
	public void setSessionFacotry(SessionFactory sessionFacotry) {
		this.sessionFacotry = sessionFacotry;
	}

	@PostConstruct
	public void injectSessionFactory() {
		super.setSessionFactory(sessionFacotry);
	}

	@Override
	public TbUser findById(String id) {
		logger.debug("getting TbUser instance with id: " + id);
		try {
			//String hql = "select u from TbUser u join fetch u.tbUserState us join fetch u.tbUserRoles ur join fetch ur.tbRole r " +
			//		"join fetch u.tbUserDepts ud join fetch ud.tbUser where u.a =  "+IDUtil.PRESERVE+" and u.UId = '"+id+"'";
			String hql = "select distinct u from TbUser u left join fetch u.tbUserState us left join fetch u.tbUserRoles ur left join fetch ur.tbRole r "+
					" left join fetch u.tbUserDepts ud left join fetch ud.tbDeptType where u.a =  "+IDUtil.PRESERVE+" and u.UId = '"+id+"'";
			List<TbUser> results = getHibernateTemplate().find(hql);
			if(results.size()>0)
				return results.get(0);
			else
				return null;
		} catch (RuntimeException re) {
			logger.error("get failed", re);
			throw re;
		}
	}
	
	
	public TbUser removeAllUserDept(String id) {
		logger.debug("getting TbUser instance with id: " + id);
		Session session = null;
		Transaction tx = null;
		try {
			
			String hql = "update TbUser set tbUserDepts=null where UId='"+id+"'";
			session = getSessionFactory().openSession();
			tx = session.beginTransaction();

			session.createQuery(hql);
			//List<TbUser> results = getHibernateTemplate().find(hql);
			//getHibernateTemplate().bulkUpdate(hql);
			//if(results.size()>0)
			//	return results.get(0);
			//else
			tx.commit();
				return null;
		} catch (RuntimeException re) {
			logger.error("get failed", re);
			if(tx != null) {
				tx.rollback();
			}
			throw re;
		}finally {
			if(session != null) {
				session.close();
			}
		}
	}
	
	/**
	 * 
	 * @param id
	 * @return hmk 查询用户（专家用DAO）
	 */
	public TbUser findByExpertUserID(String id) {
		logger.debug("getting TbUser instance with id: " + id);
		try {
			String hql = "from TbUser u left join fetch u.tbUserState us left join fetch u.tbUserRoles ur " +
					" left join fetch ur.tbRole r left join fetch u.tbUserDepts ud  where u.a = "+IDUtil.PRESERVE+" and u.UId = '"+id+"'";
			List<TbUser> results = getHibernateTemplate().find(hql);
			if(results.size()>0)
				return results.get(0);
			else
				return null;
		} catch (RuntimeException re) {
			logger.error("get failed", re);
			throw re;
		}
	}

	public TbUser findDeptById(String id) {
		logger.debug("from TbUser u join fetch u.tbDept where u.UId = '"+id+"'");
		String hql = "from TbUser u join fetch u.tbDept where u.UId = '"+id+"'";
		try {
			return (TbUser) getHibernateTemplate().find(hql).get(0);
		} catch (RuntimeException re) {
			logger.error("from TbUser u join fetch u.tbDept where u.UId failed", re);
			throw re;
		}	
	}

	public List checkUId(String hql) {
		logger.debug("seclect count TbUser instance with UId");
		try {
			return getHibernateTemplate().find(hql);
		} catch (RuntimeException re) {
			logger.error("seclect count TbUser instance with UId failed", re);
			throw re;
		}
	}

	public List query(final String hsql, final int firstRow, final int maxRow)
			throws Exception {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException,
					SQLException {
				Query query = s.createQuery(hsql);
				query.setFirstResult(firstRow);
				query.setMaxResults(maxRow);
				return query.list();
			}
		});
	}

	public List queryCount(String countsql) {
		logger.debug("query Tbuser count ");
		try {
			return getHibernateTemplate().find(countsql);
		} catch (RuntimeException re) {
			logger.error("query Tbuser count failed", re);
			throw re;
		}
	}
}
